import { onMounted } from "vue";
import type { App } from "vue";

type Options = {
  el: string;
};

const useBase64 = (options: Options): Promise<{ base64: string }> => {
  return new Promise((resolve, reject) => {
    onMounted(() => {
      const el: HTMLImageElement = document.querySelector(
        options.el
      ) as HTMLImageElement;

      console.log(el);
      el.onload = () => {
        resolve({
          base64: base64(el),
        });
      };
    });
    const base64 = (el: HTMLImageElement) => {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      canvas.width = el.width;
      canvas.width = el.height;
      ctx?.drawImage(el, 0, 0, canvas.width, canvas.width);
      return canvas.toDataURL("image/png");
    };
  });
};

// interSectionObserver 主要侦听元素是否在视窗内
// MutationObserver 主要侦听子集的变化 还有属性的变化 以及增删改查
// ResizeObserver 主要侦听元素大小的变化
const useResize = (el: HTMLImageElement, callback: Function) => {
  const resize = new ResizeObserver((entries) => {
    callback(entries);
  });
  resize.observe(el);
};

// app.use()的时候会进入到这个函数
const install = (app: App) => {
  app.directive("resize", {
    mounted(el, binding) {
      useResize(el, binding.value);
    },
  });
};
useResize.install = install;

export { useResize, useBase64 };
